<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="along&#39;s blog">
  <meta name="keyword" content="hexo-theme, vuejs">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      vue虚拟dom | ALONG
    
  </title>
  <link href="/cdn.along/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="/cdn.along/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="/cdn.along/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
  <script src="/cdn.along/jquery/3.2.1/jquery.min.js"></script>
  <script src="/cdn.along/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="/cdn.along/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
  
  
    <!-- MathJax support START -->
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="/cdn.along/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <!-- MathJax support END -->
  


  
  
    
<script src="/js/local-search.js"></script>


<meta name="generator" content="Hexo 5.4.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>
  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>ALONG</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">Home</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">Tags</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">Archives</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">About</a>
          
        </li>
      
      
        <li class="menu-item menu-item-search right-list">
    <a role="button" class="popup-trigger">
        <i class="fa fa-search fa-fw"></i>
    </a>
</li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">Home</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">Tags</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">Archives</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">About</a>
            
          </li>
        
      </ul>
    </div>
    
      <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
            <span class="search-icon">
                <i class="fa fa-search"></i>
            </span>
            <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off"
                    placeholder="Please enter your keyword(s) to search." spellcheck="false"
                    type="search" class="search-input">
            </div>
            <span class="popup-btn-close">
                <i class="fa fa-times-circle"></i>
            </span>
        </div>
        <div id="search-result">
            <div id="no-result">
                <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
            </div>
        </div>
    </div>
</div>
    
  </div>
</header>

    <div id="article-banner">
  <h2>vue虚拟dom</h2>
  <p class="post-date">2020-08-27</p>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h2 id="虚拟dom"><a href="#虚拟dom" class="headerlink" title="虚拟dom"></a>虚拟dom</h2><ul>
<li>避免直接操作dom，提高开发效率</li>
<li>作为中间层实现跨平台</li>
<li>复杂视图提高性能</li>
</ul>
<h3 id="h函数"><a href="#h函数" class="headerlink" title="h函数"></a>h函数</h3><p>h函数，内部会调用createElement，在core/vdom/create-element.js中定义</p>
<p>createElement接收多个参数，在调用时可以传递不同类型的参数，因此createElement函数做的事情就是判断用户传递的参数类型，并处理整合参数，传递给_createElement</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">createElement</span> (<span class="params"></span></span></span><br><span class="line"><span class="function"><span class="params">  context: Component,</span></span></span><br><span class="line"><span class="function"><span class="params">  tag: any,</span></span></span><br><span class="line"><span class="function"><span class="params">  data: any,</span></span></span><br><span class="line"><span class="function"><span class="params">  children: any,</span></span></span><br><span class="line"><span class="function"><span class="params">  normalizationType: any,</span></span></span><br><span class="line"><span class="function"><span class="params">  alwaysNormalize: boolean</span></span></span><br><span class="line"><span class="function"><span class="params"></span>): <span class="title">VNode</span> | <span class="title">Array</span>&lt;<span class="title">VNode</span>&gt; </span>&#123;</span><br><span class="line">    <span class="comment">// 如果data是数组或者字符串</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="built_in">Array</span>.isArray(data) || isPrimitive(data)) &#123;</span><br><span class="line">    normalizationType = children</span><br><span class="line">    children = data</span><br><span class="line">    data = <span class="literal">undefined</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 如果使用户传入render函数，alwaysNormalize = true</span></span><br><span class="line">  <span class="keyword">if</span> (isTrue(alwaysNormalize)) &#123;</span><br><span class="line">    normalizationType = ALWAYS_NORMALIZE</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> _createElement(context, tag, data, children, normalizationType)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>_createElement中返回VNode</p>
<ol>
<li>首先判断data存在且存在__ob__属性,警告并返回空VNode</li>
<li>接下来判断data存在且有is属性，将data.is赋值给tag（is用于动态的绑定组件<component v-bind:is="Com"/>）</li>
<li>接下来判断tag如果不存在(相当于给is指令设置了false)，返回空VNode</li>
<li>如果data属性有key且key不是原始值，发出警告</li>
<li>接下来处理插槽</li>
<li>然后判断normalizationType是2，代表用户传递的render函数，此时借助normalizeChildren对children进行处理，并赋值给children<ul>
<li>判断如果children是原始值<ul>
<li>通过createTextVNode创建文本节点并作为数组第一项返回这个数组（处理数组方便后期统一childrend的类型）</li>
</ul>
</li>
<li>如果children不是原始值，判断children是否是数组<ul>
<li>是，通过normalizeArrayChildren处理数组并返回,这个函数作用是如果children项也是数组，递归调用处理成一维数组</li>
<li>否，返回undefined</li>
</ul>
</li>
</ul>
</li>
<li>判断normalizationType是1，调用simpleMormalizeChildren处理数组并赋值给children，将children处理成一维数组</li>
<li>tag如果是字符串<ul>
<li>是字符串判断tag是否是html标签，创建VNode</li>
<li>如果是自定义组件，从context.$options.components中找到组件，并通过createComponent创建组件的VNode</li>
<li>以上都不满足，说明tag是自定义标签，创建一个VNode对象</li>
</ul>
</li>
<li>tag不是字符串说明是组件，通过createComponent创建组件VNode</li>
<li>接下来判断之前穿件vnode是否是数组<ul>
<li>是，直接返回vnode</li>
<li>否则，判断vnode是不是存在，存在的话，对vnode进行简单处理</li>
<li>以上都不满足，返回空VNode</li>
</ul>
</li>
</ol>
<h3 id="update"><a href="#update" class="headerlink" title="update"></a>update</h3><p>vm._update方法接收通过vm._render创建好的VNode对象，_update方法内部调用了vm.__patch__方法</p>
<p>_update原理，获取vm实例上的_vnode,如果_vnode存在，说明不是首次渲染，通过__patch__对比新旧vnode；如果_vnode不存在会将vm.$el作为第一个参数传入，__patch__内部会将真实dom处理成vnode。最中__patch__返回一个真实dom,保存到vm.$el上</p>
<h3 id="patch"><a href="#patch" class="headerlink" title="patch"></a><strong>patch</strong></h3><p>__patch__函数是通过createPatchFunction函数返回，createPatchFunction接收一个对象，返回一个patch函数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">createPatchFunction(&#123;</span><br><span class="line">    nodeOps, <span class="comment">// 定义dom操作的函数</span></span><br><span class="line">    modules <span class="comment">// 模块集合attrs,klass,events,domProps,style,transition     指令，ref</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<ol>
<li>将模块的钩子函数都保存到cbs数组中</li>
<li>返回一个patch函数<ul>
<li>判断新的VNode如果不存在，判断老VNode存在，执行Destory钩子函数</li>
<li>定义新插入vnode节点的队列</li>
<li>老vnode不存在（$mount方法调用没有传递挂载位置时）,创建节点到内存中</li>
<li>老vnode存在<ul>
<li>如果oldVnode.nodeType不存在，并且oldVnode和newVnode是sameVnode，通过patchVnode更新</li>
<li>如果上一条件不成立<ul>
<li>判断是否存在oldVnode.nodeType,如果存在说明是首次渲染,通过emptyNodeAt返回值赋值给oldVnode.elm,将真实dom转换成虚拟dom</li>
</ul>
</li>
<li>获取oldelm,获取parentElm</li>
<li>通过createElm,将newvnode转换成dom，挂载到parentElm上,插入到oldElm之前，并把newVnode记录到insertedVnodeQueue</li>
<li>判断parentEle是否存在，存在的话通过removeVnodes删除oldVnode并触发钩子函数</li>
<li>如果parentEle不存在，且oldVnode存在tag属性，触发destroy钩子</li>
</ul>
</li>
<li>如果挂载到了dom上触发insertedVnodeQueue队列中的所有insert钩子</li>
</ul>
</li>
</ol>
</section>
    <!-- Tags START -->
    
      <div class="tags">
        <span>Tags:</span>
        
  <a href="/tags#vue" >
    <span class="tag-code">vue</span>
  </a>

  <a href="/tags#虚拟dom" >
    <span class="tag-code">虚拟dom</span>
  </a>

      </div>
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/2020/08/27/vue%E5%93%8D%E5%BA%94%E5%BC%8F%E5%8E%9F%E7%90%86/">
        <span class="nav-arrow">← </span>
        
          vue响应式原理
        
      </a>
    
    
      <a class="nav-right" href="/2020/09/04/%E5%A4%87%E5%BF%98/">
        
          备忘
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">若你觉得我的文章对你有帮助，欢迎点击上方按钮对我打赏</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- No Comment -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
    <strong class="toc-title">Catalog</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#%E8%99%9A%E6%8B%9Fdom"><span class="toc-nav-text">虚拟dom</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#h%E5%87%BD%E6%95%B0"><span class="toc-nav-text">h函数</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#update"><span class="toc-nav-text">update</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#patch"><span class="toc-nav-text">patch</span></a></li></ol></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'https://github.com/alongithub/2020/08/27/虚拟dom/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', '/css/images/error_icon.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== '/css/images/error_icon.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>






    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
  <p class="copyright">
    Copyright&copy; 2019-2022 along
    <br>
    <a href="https://beian.miit.gov.cn/" target="_blank">京ICP备2020044791号-1</a>
    <!-- <br>
    Theme by <a href="https://github.com/alongithub">alongithub</a>
     -->
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("/cdn.along/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("/cdn.along/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      hljs.configure({useBR: true});
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>
<!-- Baidu Tongji -->


<script src="/js/script.js"></script>


  </body>
</html>